import {
	Controller,
	Post,
	UseInterceptors,
	UploadedFile,
	Get,
	Param,
	Delete,
	HttpException,
	HttpStatus,
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { UploadService } from "./upload.service";
import { Upload } from "./entities/upload.entity";

@Controller("uploads")
export class UploadController {
	constructor(private readonly uploadService: UploadService) {}

	@Post()
	@UseInterceptors(FileInterceptor("file"))
	async uploadFile(@UploadedFile() file: any) {
		try {
			if (!file) {
				throw new HttpException("未上传文件", HttpStatus.BAD_REQUEST);
			}

			const upload = await this.uploadService.create(file);

			return {
				code: 200,
				data: upload,
				message: "文件上传成功",
			};
		} catch (error) {
			throw new HttpException(
				error.message || "文件上传失败",
				error.status || HttpStatus.INTERNAL_SERVER_ERROR
			);
		}
	}

	@Get()
	async findAll() {
		const uploads = await this.uploadService.findAll();
		return {
			code: 200,
			data: uploads,
			message: "获取文件列表成功",
		};
	}

	@Get(":id")
	async findOne(@Param("id") id: string) {
		const upload = await this.uploadService.findOne(+id);
		if (!upload) {
			throw new HttpException("文件不存在", HttpStatus.NOT_FOUND);
		}
		return {
			code: 200,
			data: upload,
			message: "获取文件成功",
		};
	}

	@Delete(":id")
	async remove(@Param("id") id: string) {
		await this.uploadService.remove(+id);
		return {
			code: 200,
			message: "删除文件成功",
		};
	}
}
